package com.example.smartcitydemo.ui

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.core.content.edit
import androidx.databinding.DataBindingUtil
import com.blankj.utilcode.util.ToastUtils
import com.example.smartcity_jscs.network.ResultStates.Resource
import com.example.smartcitydemo.AUTHORITY
import com.example.smartcitydemo.MyApplication
import com.example.smartcitydemo.R
import com.example.smartcitydemo.bean.LoginBean
import com.example.smartcitydemo.databinding.ActivityLoginBinding
import com.example.smartcitydemo.viewModel.home.HomeViewModel

class LoginActivity : AppCompatActivity() {
    val homeViewModel: HomeViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val contentView =
            DataBindingUtil.setContentView<ActivityLoginBinding>(this, R.layout.activity_login)
        initView(contentView)
        addObserver(contentView)
    }

    private fun addObserver(contentView: ActivityLoginBinding?) {
        homeViewModel.doLoginResult.observe(this) {
            if(it is Resource.Success){
                MyApplication.sp.edit {
                    putString(AUTHORITY,it.data)
                }
                finish()
            }
        }
    }

    private fun initView(contentView: ActivityLoginBinding) {
        contentView.run {
            button2.setOnClickListener {
                val usernameText = edUsername.editText?.text?.trim().toString()
                val passwordText = edPassword.editText?.text?.trim().toString()
                if (usernameText.isEmpty()) {
                    ToastUtils.showShort("请输入用户名")
                } else if (passwordText.isEmpty()) {
                    ToastUtils.showShort("请输入密码")
                } else {
                    homeViewModel.doLogin(LoginBean(passwordText, usernameText))
                }
            }
        }
    }

    companion object {
        fun jumpToLogin(context: Context) {
            MyApplication.handler.postDelayed({
                val intent = Intent(context, LoginActivity::class.java)
                //intent的flag加上
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                context.startActivity(intent)
            }, 800)
        }
    }


}